package de.ubschmidt.capi;

import de.ubschmidt.capi.util.Bits;
import java.nio.ByteBuffer;

/**
 *
 */
public class CipMask
        implements ByteBufferWritable {

    private int _cipMask = 0;

    /**
     * Creates a new, empty {@code CipMask}.
     *
     * <p>Clearing all bits in the CIP Mask disables the signaling of
     * incoming calls to the application.
     *
     * <p>Calling party number/subaddress are used only for external
     * ISDN equipment (handsets), which might need the (local) line\u2019s
     * own address to handle outgoing calls.
     */
    public CipMask() {
    }

    /**
     * Sets the specified bit within the CipMask.
     *
     * @param cip The CIP to set.
     */
    public void set(final Cip cip) {
        _cipMask = Bits.setBit(_cipMask, cip.getValue());
    }

    /**
     * Clears the specified bit within the CipMask.
     *
     * @param cip The CIP to clear.
     */
    public void clear(final Cip cip) {
        _cipMask = Bits.clearBit(_cipMask, cip.getValue());
    }

    /**
     * Test for the specified CipMaskBit.
     *
     * @param cip
     * @return True, if the specified bit is set, otherwise false.
     */
    public boolean isSet(final Cip cip) {
        return Bits.isBitSet(_cipMask, cip.getValue());
    }

    /** {@inheritDoc} */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();

        sb.append(getClass().getSimpleName());
        sb.append("[");

        Cip [] cip = Cip.values();
        for (int i = 0; i < cip.length; ++i) {
            boolean needSeparator = false;
            if (Bits.isBitSet(_cipMask, cip[i].getValue())) {
                if (needSeparator) {
                    sb.append(" ");
                }

                sb.append(cip[i]);
                needSeparator = true;
            }
        }

        sb.append("]");

        return sb.toString();
    }

    /** {@inheritDoc} */
    public void writeTo(final ByteBuffer byteBuffer) {
        byteBuffer.putInt(_cipMask);
    }

}
